from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.db import connection
import json
from datetime import datetime
from .models import HotWord, CrawlerLog

@csrf_exempt
@require_http_methods(["GET"])
def get_hotwords(request):
    """获取热点词列表"""
    try:
        page = int(request.GET.get('page', 1))
        size = int(request.GET.get('size', 10))
        word = request.GET.get('word', '')
        category = request.GET.get('category', '')
        min_frequency = request.GET.get('min_frequency')
        max_frequency = request.GET.get('max_frequency')
        
        # 使用Django ORM查询
        queryset = HotWord.objects.all()
        
        if word:
            queryset = queryset.filter(keyword__icontains=word)
        
        if category:
            queryset = queryset.filter(category=category)
        
        if min_frequency:
            queryset = queryset.filter(hot_value__gte=int(min_frequency))
        
        if max_frequency:
            queryset = queryset.filter(hot_value__lte=int(max_frequency))
        
        total = queryset.count()
        
        # 分页
        offset = (page - 1) * size
        results = queryset[offset:offset + size]
        
        # 格式化数据
        data_list = []
        for item in results:
            data_list.append({
                'id': item.id,
                'word': item.keyword,
                'category': item.category,
                'frequency': item.hot_value,
                'similarity': getattr(item, 'similarity', 0),
                'trend': 'up',
                'created_at': item.created_at.isoformat(),
                'updated_at': item.updated_at.isoformat()
            })
        
        return JsonResponse({
            'code': 200,
            'message': 'success',
            'data': {
                'list': data_list,
                'total': total,
                'page': page,
                'size': size
            }
        })
            
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': str(e),
            'data': None
        })

@csrf_exempt
@require_http_methods(["POST"])
def add_hotword(request):
    """添加热点词"""
    try:
        data = json.loads(request.body)
        word = data.get('word')
        category = data.get('category')
        frequency = data.get('frequency', 0)
        similarity = data.get('similarity', 0)
        
        if not word or not category:
            return JsonResponse({
                'code': 400,
                'message': 'word and category are required',
                'data': None
            })
        
        hotword = HotWord.objects.create(
            keyword=word,
            category=category,
            hot_value=frequency,
            similarity=similarity
        )
        
        result = {
            'id': hotword.id,
            'word': hotword.keyword,
            'category': hotword.category,
            'frequency': hotword.hot_value,
            'similarity': hotword.similarity,
            'trend': 'up',
            'created_at': hotword.created_at.isoformat(),
            'updated_at': hotword.updated_at.isoformat()
        }
        
        return JsonResponse({
            'code': 200,
            'message': 'success',
            'data': result
        })
            
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': str(e),
            'data': None
        })

@csrf_exempt
@require_http_methods(["PUT"])
def update_hotword(request, hotword_id):
    """更新热点词"""
    try:
        data = json.loads(request.body)
        word = data.get('word')
        category = data.get('category')
        frequency = data.get('frequency')
        similarity = data.get('similarity')
        
        try:
            hotword = HotWord.objects.get(id=hotword_id)
            
            if word is not None:
                hotword.keyword = word
            if category is not None:
                hotword.category = category
            if frequency is not None:
                hotword.hot_value = frequency
            if similarity is not None:
                hotword.similarity = similarity
                
            hotword.save()
            
            result = {
                'id': hotword.id,
                'word': hotword.keyword,
                'category': hotword.category,
                'frequency': hotword.hot_value,
                'similarity': hotword.similarity,
                'trend': 'up',
                'created_at': hotword.created_at.isoformat(),
                'updated_at': hotword.updated_at.isoformat()
            }
            
            return JsonResponse({
                'code': 200,
                'message': 'success',
                'data': result
            })
            
        except HotWord.DoesNotExist:
            return JsonResponse({
                'code': 404,
                'message': 'Hotword not found',
                'data': None
            })
            
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': str(e),
            'data': None
        })

@csrf_exempt
@require_http_methods(["DELETE"])
def delete_hotword(request, hotword_id):
    """删除热点词"""
    try:
        try:
            hotword = HotWord.objects.get(id=hotword_id)
            hotword.delete()
            
            return JsonResponse({
                'code': 200,
                'message': 'success',
                'data': None
            })
            
        except HotWord.DoesNotExist:
            return JsonResponse({
                'code': 404,
                'message': 'Hotword not found',
                'data': None
            })
            
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': str(e),
            'data': None
        })

@csrf_exempt
@require_http_methods(["GET"])
def get_hotword_categories(request):
    """获取热点词分类列表"""
    try:
        categories = HotWord.objects.values_list('category', flat=True).distinct().order_by('category')
        
        return JsonResponse({
            'code': 200,
            'message': 'success',
            'data': list(categories)
        })
            
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': str(e),
            'data': None
        })


# crawler/views.py

@csrf_exempt
@require_http_methods(["POST"])
def start_hotword_crawler(request):
    """启动热点词爬虫"""
    try:
        # 记录开始日志
        log = CrawlerLog.objects.create(
            status='running',
            message='爬虫任务已启动'
        )

        # 直接调用命令类
        try:
            from crawler.management.commands.crawl_douyin import Command
            command = Command()
            command.handle()

            # 更新日志状态
            log.status = 'success'
            log.message = '爬虫任务执行成功'
            log.save()

            return JsonResponse({
                'code': 200,
                'message': 'Crawler started successfully',
                'data': {'taskId': f'task-{log.id}'}
            })
        except Exception as cmd_error:
            # 记录具体的命令执行错误
            log.status = 'failed'
            log.message = f'爬虫命令执行失败: {str(cmd_error)}'
            log.save()

            import traceback
            print(f"爬虫执行错误详情: {traceback.format_exc()}")

            return JsonResponse({
                'code': 500,
                'message': f'Crawler execution failed: {str(cmd_error)}',
                'data': None
            })

    except Exception as e:
        # 记录视图函数层面的失败日志
        try:
            CrawlerLog.objects.create(
                status='failed',
                message=f'视图函数错误: {str(e)}'
            )
        except:
            pass  # 如果日志记录也失败，至少返回错误给前端

        return JsonResponse({
            'code': 500,
            'message': f'View function error: {str(e)}',
            'data': None
        })

